﻿using GalaSoft.MvvmLight.Command;
using Microsoft.Practices.ServiceLocation;
using MuddyBoots.Greenlight.QC.Common.Patterns.Behaviour.Mediator;
using MuddyBoots.GreenlightQC.DataService;
using MuddyBoots.GreenlightQC.DataService.Enumeration;
using MuddyBoots.GreenlightQC.Mobile.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace MuddyBoots.GreenlightQC.Mobile.UI.ViewModel
{
    public class LoginViewModel : ViewModel
    {
        private bool notLoggedIn = true;

        public string Username { get; set; }

        public bool NotLoggedIn
        {
            get
            {
                return this.notLoggedIn;
            }

            set
            {
                this.notLoggedIn = value;
                this.RaisePropertyChanged("NotLoggedIn");
            }
        }

        public ICommand LogInCommand
        {
            get
            {
                return new RelayCommand<object>(this.LogInCommandExecute);
            }
        }

        private void LogInCommandExecute(object parameter)
        {
            var passwordBox = parameter as PasswordBox;
            if (passwordBox != null)
            {
                try
                {
                    this.Login(passwordBox);
                }
                catch (UnauthorizedAccessException e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        private void Login(PasswordBox passwordBox)
        {
            var service = ServiceLocator.Current.GetInstance<IGreenlightQCMobile>();
            var database = ServiceLocator.Current.GetInstance<IDatabaseEntities>();
            var user = service.LogIn(database, this.Username, passwordBox.Password);
            if (user.AccountStatus == UserAccountStatus.Valid)
            {
                this.NotLoggedIn = false;
                Mediator.NotifyColleagues("LoggedIn", null);
            }
        }
    }
}
